import _ from "lodash";
import { onMounted } from "vue";
import { onUnmounted } from "vue";

// 大屏适配
export default function useScalePage(option) {
    // 节流
    const resizeFunc = _.throttle(() => {
        // 页面加载完成后触发缩放
        triggerScale();
    }, 100);

    onMounted(() => {
        // 页面加载完成后触发缩放
        triggerScale();
        // 窗口大小变化时重新计算缩放
        window.addEventListener("resize", resizeFunc);
    });

    onUnmounted(() => {
        // 移除事件监听器释放资源
        window.removeEventListener("resize", resizeFunc);
    });

    // 大屏适配
    function triggerScale() {
        // 1. 获取设计稿的宽高
        let targetX = option.targetX || 1920;
        let targetY = option.targetY || 1080;
        let targetRatio = option.targetRatio || 16 / 9;
        // 2. 获取当前设备的宽高
        let currentX =
            document.documentElement.clientWidth || document.body.clientWidth;
        let currentY =
            document.documentElement.clientHeight || document.body.clientHeight;
        // 3. 计算缩放比例
        let scaleRatio = currentX / targetX; // 参照宽度进行缩放
        let currentRatio = currentX / currentY; // 当前设备比例
        // 超宽屏
        if (currentRatio > targetRatio) {
            scaleRatio = currentY / targetY; // 参照高度进行缩放
            document.body.style = `width:${targetX}px; height:${targetY}px; transform: scale(${scaleRatio}) translateX(-50%); left:50%`; // 缩放
        } else {
            // 4. 设置缩放比例
            document.body.style = `width:${targetX}px; height:${targetY}px; transform: scale(${scaleRatio})`;
        }
    }
}